;(function () {
    /**
     * ScrollFix v0.1
     * http://www.joelambert.co.uk
     *
     * Copyright 2011, Joe Lambert.
     * Free to use under the MIT license.
     * http://www.opensource.org/licenses/mit-license.php
     */

    var ScrollFix = function (elem) {
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (isAndroid) {
            return;
        }

        // Variables to track inputs
        var startY, startTopScroll;

        elem = elem || document.querySelector(elem);

        // If there is no element, then do nothing
        if (!elem)
            return;

        // Handle the start of interactions
        elem.addEventListener('touchstart', function (event) {
            startY = event.touches[0].pageY;
            startTopScroll = elem.scrollTop;
            if (startTopScroll <= 0)
                elem.scrollTop = 1;

            if (startTopScroll + elem.offsetHeight >= elem.scrollHeight)
                elem.scrollTop = elem.scrollHeight - elem.offsetHeight - 1;
        }, false);

        var HEADER_ELEM = document.querySelector(".ui-header");
        var FOOTER_ELEM = document.querySelector(".ui-footer");

        // if (HEADER_ELEM) {
        //     HEADER_ELEM.addEventListener('touchmove', function (e) {
        //         e.stopPropagation();
        //         e.preventDefault();
        //         return false;
        //     });
        // }

        if (FOOTER_ELEM) {
            FOOTER_ELEM.addEventListener('touchmove', function (e) {
                e.stopPropagation();
                e.preventDefault();
                return false;
            });
        }

    };
    var SRCOLL_ELEM = document.querySelector(".ui-page");
    ScrollFix(SRCOLL_ELEM);

})();

// .container 设置了 overflow 属性, 导致 Android 手机下输入框获取焦点时, 输入法挡住输入框的 bug
// 相关 issue: https://github.com/weui/weui/issues/15
// 解决方法:
// 0. .container 去掉 overflow 属性, 但此 demo 下会引发别的问题
// 1. 参考 http://stackoverflow.com/questions/23757345/android-does-not-correctly-scroll-on-input-focus-if-not-body-element
//    Android 手机下, input 或 textarea 元素聚焦时, 主动滚一把
if (/Android/gi.test(navigator.userAgent)) {
    window.addEventListener('resize', function () {
        if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
            window.setTimeout(function () {
                document.activeElement.scrollIntoViewIfNeeded();
            }, 0);
        }
    })
}